package com.ecnu.web.controller.tool;

import com.alibaba.fastjson2.JSON;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.HttpCode;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.HttpUtils;
import com.ecnu.common.utils.ip.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.HashMap;

@Api(tags = "第三方对接")
@RestController
@RequestMapping("/cnki")
@Validated
public class CNKIController extends BaseController {

    @ApiOperation(value = "获取token")
    @GetMapping("/getToken")
    public AjaxResult getToken() {
        LoginUser loginUser = getLoginUser();
        //访问地址
        String url = "https://my.cnki.net/IntegrateLogin/api/IntegrateLoginApi/UserLogin";
        //包装参数
        HashMap<String, String> map = new HashMap<>();
        map.put("Key", "278F09ED-D6C6-4925-25DC-0CA7C9051631");//学校秘钥
        map.put("UserName", "hdsfjjyglxb");//学校名称
        map.put("UserIp", IpUtils.getIpAddr());//用户客户端ip
        map.put("SubUserName", String.valueOf(loginUser.getUserId()));//登录用户id
        System.out.println("map = " + map);
        String jsonString = JSON.toJSONString(map);

        String contentType = "application/json";
        //访问返回
        String token = HttpUtils.sendPost(url, jsonString, contentType,new HashMap<>());
        if (StringUtils.isBlank(token)) {
            return AjaxResult.error("生成token错误，请联系管理员处理！！！");
        }
        HttpCode httpCode = JSON.parseObject(token, HttpCode.class);
        if (httpCode.getCode().equals("0")) {
            return AjaxResult.error(httpCode.getMessage());
        }
        HashMap<String, String> ret = new HashMap<>();
        ret.put("url", "https://my.cnki.net/IntegrateLogin/Redirect/Index");//访问地址
        ret.put("token", httpCode.getToken());//生成的token
        ret.put("SubUserName", String.valueOf(loginUser.getUserId()));//登录用户id
        ret.put("ReturnUrl",URLEncoder.encode("https://x.cnki.net"));//跳转地址

        String geturl=ret.get("url")+"?token="+ret.get("token")+"&ReturnUrl="+ ret.get("ReturnUrl")+"&SubUserName="+ret.get("SubUserName");
        return AjaxResult.success(geturl);
    }
}
